package com.javacv.plus.starter;

import com.javacv.plus.platform.Platform;
import com.javacv.plus.platform.PlatformDetector;
import com.javacv.plus.platform.SystemInfo;
import com.javacv.plus.extensions.image.ImageProcessor;
import com.javacv.plus.extensions.image.config.ImageConfig;
import lombok.extern.slf4j.Slf4j;

/**
 * JavaCV Plus 启动器
 * 提供一键初始化和简化配置功能
 */
@Slf4j
public class JavaCVPlusStarter {
    
    private static boolean initialized = false;
    private static Platform currentPlatform;
    private static SystemInfo systemInfo;
    private static ImageConfig defaultImageConfig;
    
    /**
     * 初始化JavaCV Plus
     */
    public static void initialize() {
        if (initialized) {
            log.debug("JavaCV Plus已经初始化过了");
            return;
        }
        
        log.info("🚀 初始化JavaCV Plus...");
        
        try {
            // 检测平台
            currentPlatform = PlatformDetector.detectCurrentPlatform();
            systemInfo = PlatformDetector.getSystemInfo();
            
            log.info("✅ 平台检测完成: {}", currentPlatform.getPlatformString());
            log.info("📊 系统信息: {} {} ({})", 
                    systemInfo.getOsName(), 
                    systemInfo.getOsVersion(), 
                    systemInfo.getOsArch());
            
            // 创建默认配置
            createDefaultConfiguration();
            
            initialized = true;
            log.info("🎉 JavaCV Plus初始化完成!");
            
        } catch (Exception e) {
            log.error("❌ JavaCV Plus初始化失败", e);
            throw new RuntimeException("JavaCV Plus初始化失败", e);
        }
    }
    
    /**
     * 创建默认配置
     */
    private static void createDefaultConfiguration() {
        ImageConfig.ImageConfigBuilder builder = ImageConfig.imageBuilder()
                .quality(85)
                .outputFormat("jpg")
                .keepAspectRatio(true);
        
        // 根据系统性能调整配置
        if (systemInfo.getMaxMemory() >= 8L * 1024 * 1024 * 1024) {
            // 大内存系统：高质量配置
            builder.quality(95);
            log.info("🧠 大内存系统 - 启用高质量配置");
        } else if (systemInfo.getMaxMemory() >= 4L * 1024 * 1024 * 1024) {
            // 中等内存系统：平衡配置
            builder.quality(85);
            log.info("💾 中等内存系统 - 启用平衡配置");
        } else {
            // 小内存系统：性能优先配置
            builder.quality(75);
            log.info("⚡ 小内存系统 - 启用性能优先配置");
        }
        
        defaultImageConfig = builder.build();
        log.info("🔧 默认配置创建完成 - 质量: {}%, 格式: {}", 
                defaultImageConfig.getQuality(), 
                defaultImageConfig.getOutputFormat());
    }
    
    /**
     * 获取图像处理器（使用默认配置）
     */
    public static ImageProcessor createImageProcessor(String imagePath) {
        ensureInitialized();
        return ImageProcessor.of(imagePath, defaultImageConfig);
    }
    
    /**
     * 获取图像处理器（使用自定义配置）
     */
    public static ImageProcessor createImageProcessor(String imagePath, ImageConfig config) {
        ensureInitialized();
        return ImageProcessor.of(imagePath, config);
    }
    
    /**
     * 获取当前平台信息
     */
    public static Platform getCurrentPlatform() {
        ensureInitialized();
        return currentPlatform;
    }
    
    /**
     * 获取系统信息
     */
    public static SystemInfo getSystemInfo() {
        ensureInitialized();
        return systemInfo;
    }
    
    /**
     * 获取默认图像配置
     */
    public static ImageConfig getDefaultImageConfig() {
        ensureInitialized();
        return defaultImageConfig;
    }
    
    /**
     * 是否已初始化
     */
    public static boolean isInitialized() {
        return initialized;
    }
    
    /**
     * 打印系统信息和建议配置
     */
    public static void printSystemInfo() {
        ensureInitialized();
        
        String separator = new String(new char[60]).replace('\0', '=');
        log.info("\n" + separator);
        log.info("                JavaCV Plus 系统信息");
        log.info(separator);
        log.info("🖥️  平台: {}", currentPlatform.getPlatformString());
        log.info("💻 系统: {} {} ({})", 
                systemInfo.getOsName(), 
                systemInfo.getOsVersion(), 
                systemInfo.getOsArch());
        log.info("🔢 CPU核心: {}", systemInfo.getAvailableProcessors());
        log.info("💾 最大内存: {}", SystemInfo.formatMemorySize(systemInfo.getMaxMemory()));
        log.info("📱 是否桌面平台: {}", currentPlatform.isDesktop());
        
        log.info("\n🔧 当前默认配置:");
        log.info("   图像质量: {}%", defaultImageConfig.getQuality());
        log.info("   输出格式: {}", defaultImageConfig.getOutputFormat().toUpperCase());
        log.info("   保持宽高比: {}", defaultImageConfig.isKeepAspectRatio());
        
        log.info("\n💡 性能建议:");
        if (systemInfo.getAvailableProcessors() >= 8) {
            log.info("   ✅ 多核处理器 - 推荐启用并行处理");
        }
        if (systemInfo.getMaxMemory() >= 8L * 1024 * 1024 * 1024) {
            log.info("   ✅ 大内存 - 可处理大尺寸图像");
        }
        if (currentPlatform.isARM()) {
            log.info("   ✅ ARM架构 - 优化的原生库支持");
        }
        
        log.info(separator);
    }
    
    /**
     * 确保已初始化
     */
    private static void ensureInitialized() {
        if (!initialized) {
            initialize();
        }
    }
    
    /**
     * 创建性能优化的配置
     */
    public static ImageConfig createPerformanceConfig() {
        ensureInitialized();
        return ImageConfig.imageBuilder()
                .quality(75)
                .outputFormat("jpg")
                .keepAspectRatio(true)
                .build();
    }
    
    /**
     * 创建高质量配置
     */
    public static ImageConfig createHighQualityConfig() {
        ensureInitialized();
        return ImageConfig.imageBuilder()
                .quality(95)
                .outputFormat("png")
                .keepAspectRatio(true)
                .watermarkOpacity(0.8)
                .fontSize(24)
                .build();
    }
    
    /**
     * 快速图像处理方法
     */
    public static boolean quickProcess(String inputPath, String outputPath) {
        try {
            createImageProcessor(inputPath)
                    .save(outputPath);
            return true;
        } catch (Exception e) {
            log.error("快速处理失败: {} -> {}", inputPath, outputPath, e);
            return false;
        }
    }
} 